package com.bdqn.t362.user.servlet;

import com.alibaba.fastjson.JSONObject;
import com.bdqn.t362.common.utils.JedisUtils;
import com.bdqn.t362.user.entity.UserEntity;
import com.bdqn.t362.user.service.UserService;
import com.bdqn.t362.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lqm
 * @ClassName ${NAME}
 * @description: 后台登录管理
 */
@WebServlet("/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String account = request.getParameter("username");
        String pwd = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");

        UserService userService =new UserServiceImpl();
        UserEntity userEntity=userService.findByAccountAndPwd(account,pwd);
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject();

        if(userEntity==null){//账号密码错误
            jsonObject.put("state","0");

        }else{
            if("true".equals(rememberMe)){
                //随机数
                String tokenStr = String.valueOf((int) ((Math.random()*9+1)*1000));

                JedisUtils.setString(tokenStr, JSONObject.toJSONString(userEntity));
//                HttpSession session =request.getSession();
//                Cookie cookie = new Cookie("userToken",tokenStr);
//                response.addCookie(cookie);
                jsonObject.put("tokenStr",tokenStr);

            }

            jsonObject.put("state","1");

        }
        out.print(jsonObject.toString());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
